package com.yanqu.road.dao.impl.cross;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.yanqu.road.dao.db.DbNameStrategy;
import com.yanqu.road.dao.db.DbParameter;
import com.yanqu.road.dao.impl.TempDao;
import com.yanqu.road.entity.rank.cross.CrossActivityTeamRank;
import com.yanqu.road.entity.rank.cross.TeamBaseInfo;
import com.yanqu.road.utils.string.StringUtils;

import java.math.BigInteger;
import java.sql.CallableStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

public class CrossActivityTeamRankDaoImpl extends TempDao {
    public List<CrossActivityTeamRank> getCrossActivityTeamRankList(int activityId, int groupId) {
        ResultSet rs = null;
        CallableStatement call = null;
        List<CrossActivityTeamRank> list = new ArrayList<>();
        String sql = "select * from t_c_activity_team_rank where activityId =? and groupId=?";
        try {
            getDb().setConnName(DbNameStrategy.getCross2Db());
            call = getDb().getConnection().prepareCall(sql);
            int i = 1;
            call.setInt(i++, activityId);
            call.setInt(i++, groupId);
            rs = call.executeQuery();
            while (rs.next()) {
                CrossActivityTeamRank data = initCrossActivityTeamRank(rs);
                list.add(data);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            getDb().closeConnection(call, rs);
        }
        return list;
    }

    public Map<Integer, Map<Integer, LinkedList<CrossActivityTeamRank>>> getCrossActivityTeamRankListMap(List<Integer> activityIdList) {
        ResultSet rs = null;
        CallableStatement call = null;
        Map<Integer, Map<Integer, LinkedList<CrossActivityTeamRank>>> dataMap = new ConcurrentHashMap<>();
        if(null == activityIdList || activityIdList.size() <= 0){
            return dataMap;
        }
        String sql = "select * from t_c_activity_team_rank where activityId in(" + StringUtils.listToString(activityIdList, ",") + ")";
        try {
            getDb().setConnName(DbNameStrategy.getCross2Db());
            call = getDb().getConnection().prepareCall(sql);
            rs = call.executeQuery();
            while (rs.next()) {
                CrossActivityTeamRank data = initCrossActivityTeamRank(rs);
                if(!dataMap.containsKey(data.getType())){
                    dataMap.put(data.getType(), new ConcurrentHashMap<>());
                }
                Map<Integer, LinkedList<CrossActivityTeamRank>> tempMap = dataMap.get(data.getType());
                if(!tempMap.containsKey(data.getBigRankType())){
                    tempMap.put(data.getBigRankType(), new LinkedList<>());
                }
                tempMap.get(data.getBigRankType()).add(data);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            getDb().closeConnection(call, rs);
        }
        return dataMap;
    }

    public boolean updateCrossActivityTeamRankList(List<CrossActivityTeamRank> rankList, int conditionType) {
        String sql = "REPLACE INTO t_c_activity_team_rank(activityId,groupId,conditionType,rank,teamId,serverId,teamBaseInfo,lastUpdateTime,value,param) " +
                "VALUES(?,?,?,?,?,?,?,?,?,?)";
        try {
            getDb().setConnName(DbNameStrategy.getCross2Db());
            List<Map<Integer, DbParameter>> mapList = new ArrayList<>();
            int rank = 1;
            for (CrossActivityTeamRank teamRank : rankList) {
                int i = 1;
                Map<Integer, DbParameter> para = new HashMap<>();
                para.put(i++, new DbParameter(Types.INTEGER, teamRank.getType()));
                para.put(i++, new DbParameter(Types.INTEGER, teamRank.getGroupId()));
                para.put(i++, new DbParameter(Types.INTEGER, conditionType));
                para.put(i++, new DbParameter(Types.INTEGER, rank));
                para.put(i++, new DbParameter(Types.INTEGER, teamRank.getTeamId()));
                para.put(i++, new DbParameter(Types.BIGINT, teamRank.getServerId()));
                para.put(i++, new DbParameter(Types.NVARCHAR, teamRank.getTeamBaseInfoJsonStr()));
                para.put(i++, new DbParameter(Types.BIGINT, teamRank.getLastUpdateTime()));
                para.put(i++, new DbParameter(Types.VARCHAR, teamRank.getValue().toString()));
                para.put(i++, new DbParameter(Types.VARCHAR, teamRank.getParam()));
                mapList.add(para);
                rank++;
            }
            if (getDb().executeBatchQuery(sql, mapList) > -1) {
                return true;
            }
        } catch (Exception e) {
            logger.error(Thread.currentThread().getStackTrace()[1].getMethodName() + ":", e);
        }
        return false;
    }

    private CrossActivityTeamRank initCrossActivityTeamRank(ResultSet rs) throws SQLException {
        CrossActivityTeamRank data = new CrossActivityTeamRank();
        data.setGroupId(rs.getInt("groupId"));
        data.setType(rs.getInt("activityId"));
        data.setBigRankType(rs.getInt("conditionType"));
        data.setRank(rs.getInt("rank"));
        data.setTeamId(rs.getInt("teamId"));
        String baseTeamInfoStr = rs.getString("teamBaseInfo");
        if(null == baseTeamInfoStr){
            baseTeamInfoStr = "";
        }
        TeamBaseInfo teamBaseInfo = JSON.parseObject(baseTeamInfoStr, new TypeReference<TeamBaseInfo>() {});
        if(null != teamBaseInfo){
            data.setTeamBaseInfo(teamBaseInfo);
        }
        data.setServerId(rs.getLong("serverId"));
        data.setLastUpdateTime(rs.getLong("lastUpdateTime"));
        String value = rs.getString("value");
        if(!StringUtils.isNullOrEmpty(value)) {
            data.setValue(new BigInteger(value));
        }
        data.setParam(rs.getString("param"));
        return data;
    }

}
